<template>
  <div :width="props.width" :height="props.height" :id="id"></div>
</template>

<script setup lang="ts">
import { watch, onMounted } from 'vue'
import Player from 'xgplayer'
import 'xgplayer/dist/index.min.css'
// 定义一个变量来存储 player 实例
let player: Player

const props = defineProps({
  id: {
    type: String,
    required: true,
  },
  videoUrl: {
    type: String,
    default: () => '',
  },
  playsinline: {
    type: Boolean,
    default: true,
  },
  autoplay: {
    type: Boolean,
    default: false,
  },
  loop: {
    type: Boolean,
    default: false,
  },
  width: {
    type: String,
    default: '100%',
  },
  height: {
    type: String,
    default: '100%',
  },
})

// 初始化西瓜视频
const initPlayer = () => {
  player = new Player({
    lang: 'zh',
    volume: 0.3,
    id: props.id,
    url: props.videoUrl,
    playsinline: props.playsinline,
    height: props.height,
    width: props.width,
    videoInit: true,
    pip: true,
    autoplay: props.autoplay,
    loop: props.loop,
    controls: {
      mode: 'bottom',
    },
    commonStyle: {
      // 进度条底色
      progressColor: '',
      // 播放完成部分进度条底色
      playedColor: '#ff9700',
      // 缓存部分进度条底色
      cachedColor: '',
      // 进度条滑块样式
      sliderBtnStyle: {},
      // 音量颜色
      volumeColor: '#ff9700',
    },
    playbackRate: [0.25, 0.5, 1, 1.5, 2, 3],
    whitelist: [''],
  })
}

watch(props, () => {
  if (player) player.destroy()
  initPlayer()
})
onMounted(() => {
  initPlayer()
})
</script>
